<?php

class AdminController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
        $auth = Zend_Auth::getInstance();

        if ($auth->hasIdentity() || $this->getRequest()->getActionName() == 'login') {
            
        } else {
            $this->_redirect('/admin/login');
        }
    }

    public function indexAction() {
        // action body
        $this->_helper->Layout->setLayout('admin');
    }

    public function getBlogListsAction() {
        $this->_helper->Layout->disableLayout();
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $limit = $this->_request->getParam('limit');
        $offset = $this->_request->getParam('start');
        $type = $this->_request->getParam('type');
        $search_term = $this->_request->getParam('query');
        $newBtnStatus = $this->_request->getParam('newStatus');

        $query = $db->select()
                        ->from('blog_info', array('id' => 'blog_id', 'blog_name', 'blog_url', 'feed_url', 'language', 'status', 'author_email', 'author_name'))
                        ->order('blog_name ASC');

        if ($newBtnStatus == FALSE) {
            $query->where("status = 'new'");
        } else {
            $query->where("status = 'new'");
        }
        $count = count($db->fetchAll($query));
        if (!empty($limit)) {
            $query->limit($limit, $offset);
        }

        $result = $db->fetchAll($query);
        $this->_helper->json(array('data' => $result, 'total' => $count, 'success' => true));
    }

    public function approveBlogAction() {
        $this->_helper->Layout->disableLayout();
        $payload = Zend_Json::decode($this->getRequest()->getRawBody());
        $id = $payload['id'];
        unset($payload['id']);
        $BlogDbTable = new Application_Model_DbTable_BlogInfo();
        $query = $BlogDbTable->select()
                        ->where("blog_id=?", $id);
        $oldArray = $BlogDbTable->fetchAll($query)->toArray();
        // var_dump($oldArray[0]);
        if ($oldArray[0]['status'] == 'new' && $payload['status'] == 'approved') {
            $mail = new Zend_Mail('utf-8');
            $mail->setBodyHtml("Dear " . $oldArray[0]['author_name'] . ", <br/>
Your blog " . $oldArray[0]['blog_name'] . " has been approved. visiters to <a href='http://hathmaluwa.org'>hathmaluwa.org </a> will recieve updates from your blog.
    thank you for joining with us.<br />
    If you are interested to linking back to us, please insert one of the following HTML code to your blog.
<br /><br/>
    &lt;a href=&quot;http://www.hathmaluwa.org&quot; title=&quot;hathmaluwa&quot; target=&quot;_blank&quot; &gt; &lt;img src=&quot;http://www.hathmaluwa.org/images/hathmaluwa_ext_logo.png&quot; alt=&quot;hathmaluwa&quot; /&gt; &lt;/a&gt;

<br/> <br/>
    Thank you,<br/>
     The hathmaluwa Team.
");
            $mail->addTo($oldArray[0]['author_email'], $oldArray[0]['author_name']);
            $mail->addCc('admin@hathmaluwa.org', 'admins');
            $mail->setSubject('Congratulations | Adding your blog to hathmaluwa');
            $mail->send();
            //send blog approved email
        } elseif ($oldArray[0]['status'] == 'new' && $payload['status'] == 'rejected') {
            $mail = new Zend_Mail('utf-8');
            $mail->setBodyHtml("Dear " . $oldArray[0]['author_name'] . ", <br/>
Sorry, Your blog " . $oldArray[0]['blog_name'] . " has been rejected by a hathmaluwa admin.
");
            $mail->addTo($oldArray[0]['author_email'], $oldArray[0]['author_name']);
            $mail->addCc('admin@hathmaluwa.org', 'admins');
            $mail->setSubject('Adding your blog to hathmaluwa');
            $mail->send();
            //send blog rejected email
        }
         $BlogDbTable->update($payload, "blog_id=" . $id);
        $this->_helper->json(array('success' => true));
    }

    public function deleteBlogAction() {
        $this->_helper->Layout->disableLayout();
        $payload = Zend_Json::decode($this->getRequest()->getRawBody());
        $id = $payload['id'];
        $BlogDbTable = new Application_Model_DbTable_BlogInfo();
        $BlogDbTable->delete("blog_id=" . $id);
        $this->_helper->json(array('success' => true));
    }

    public function loginAction() {
        $this->_helper->Layout->disableLayout();

        $db = Zend_Db_Table_Abstract::getDefaultAdapter();

        $loginForm = new Application_Form_Login();

        if ($loginForm->isValid($_POST)) {

            $adapter = new Zend_Auth_Adapter_DbTable(
                            $db,
                            'users',
                            'username',
                            'password',
                            'MD5(?)'
            );
            $adapter
                    ->setTableName('users')
                    ->setIdentityColumn('username')
                    ->setCredentialColumn('password')
            ;

            $adapter->setIdentity($loginForm->getValue('username'));
            $adapter->setCredential($loginForm->getValue('password'));

            $auth = Zend_Auth::getInstance();
            $result = $auth->authenticate($adapter);

            if ($result->isValid()) {
                $this->_helper->FlashMessenger('Successful Login');
                $this->_redirect('/admin/');
                return;
            } else {
                echo 'password invalid';
            }
        }

        $this->view->loginForm = $loginForm;
    }

}